package softwaretest.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import softwaretest.Domain.User;
import softwaretest.dto.AuthResponse;
import softwaretest.service.UserService;

@RestController
@RequestMapping("/api/users")
public class UserController {

    @Autowired
    private UserService userService;

    // 用户注册
    @PostMapping("/register")
    public ResponseEntity<AuthResponse> registerUser(@RequestBody User user) {
        AuthResponse response = userService.registerUser(user);
        return ResponseEntity.ok(response);
    }

    // 用户登录
    @PostMapping("/login")
    public ResponseEntity<AuthResponse> login(@RequestBody User user) {
        AuthResponse response = userService.login(user.getUsername(), user.getPassword());
        if (response.getToken() != null) {
            return ResponseEntity.ok(response); // 成功返回 Token
        }
        return ResponseEntity.status(401).body(response); // 401 状态码
    }
}